#include <windows.h>
#include <detours/detours.h>
#include <QAccessible>

#include "Log.h"

using QAccessible_isActive = bool(*)(void);
static QAccessible_isActive pOriginIsActive = &QAccessible::isActive;
using QAccessible_queryAccessibleInterface = QAccessibleInterface * (*)(QObject *);
static QAccessible_queryAccessibleInterface pOriginQueryAccessibleInterface = &QAccessible::queryAccessibleInterface;

bool myIsActive()
{
	return false;
}

QAccessibleInterface * myQueryAccessibleInterface(QObject *)
{
	return nullptr;
}

bool interceptQAcessible()
{
	DetourTransactionBegin();
	DetourUpdateThread(GetCurrentThread());
	DetourAttach(&(PVOID&)pOriginIsActive, myIsActive);
	DetourAttach(&(PVOID&)pOriginQueryAccessibleInterface, myQueryAccessibleInterface);
	LONG error = DetourTransactionCommit();
	if (error == NO_ERROR) {
		LOG_INFO("QAccessible is intercepted.");
		return true;
	}
	else {
		LOG_ERR("QAccessible isn't intercepted.");
		return false;
	}
}

bool restoreQAcessible()
{
	DetourTransactionBegin();
	DetourUpdateThread(GetCurrentThread());
	DetourDetach(&(PVOID&)pOriginIsActive, myIsActive);
	DetourDetach(&(PVOID&)pOriginQueryAccessibleInterface, myQueryAccessibleInterface);
	LONG error = DetourTransactionCommit();
	if (error == NO_ERROR) {
		LOG_INFO("QAccessible is restored.");
		return true;
	}
	else {
		LOG_ERR("QAccessible isn't restored.");
		return false;
	}
}